package com.bootdo.clouddo.security;

import com.bootdo.clouddo.domain.user.QaUsers;
import com.bootdo.clouddo.service.sms.SMSCommonService;
import com.bootdo.clouddo.utils.spring.MD5SaltPasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 
 * @author WD
 *
 */
public class VpanAuthenticationProvider extends DaoAuthenticationProvider  {

    public static final String SMS_LOGIN_VCODE = "sms_login_vcode_";
	
	@Autowired
	private SMSCommonService sMSCommonService;
	
	@Autowired
    MD5SaltPasswordEncoder encoder;
	
	@Override
    protected void additionalAuthenticationChecks(UserDetails userDetails,
            UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        Object salt = null;
        
        QaUsers user = (QaUsers) userDetails;

        //微信登录，直接放行
        if(QaUsers.LOGIN_WAY_WXCODE.equals(user.getCurrentLoginWay())
                || QaUsers.LOGIN_WAY_WXOPENID.equals(user.getCurrentLoginWay())){
            return;
        }
        if (super.getSaltSource() != null) {
            salt = super.getSaltSource().getSalt(userDetails);
        }else
        	salt = user.getSalt();

        if (authentication.getCredentials() == null) {
            logger.debug("Authentication failed: no credentials provided");

            throw new BadCredentialsException(messages.getMessage(
                    "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
        }

        String presentedPassword = authentication.getCredentials().toString();
        if(QaUsers.LOGIN_WAY_PWD.equals(user.getCurrentLoginWay())){//密码登陆
	        if (!encoder.matches(presentedPassword, userDetails.getPassword(), String.valueOf(salt))) {
	            logger.debug("Authentication failed: password does not match stored value");
	            throw new BadCredentialsException(messages.getMessage(
	                    "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
	        }
        }
        else if(QaUsers.LOGIN_WAY_SMS.equals(user.getCurrentLoginWay())){//短信登陆
        	if(!sMSCommonService.ifVerifyCodeValid(presentedPassword, SMS_LOGIN_VCODE + user.getMobile())){
        		  logger.debug("Authentication failed: SMS vcode does not match stored value");
  	            throw new BadCredentialsException("SMS vcode invalid");
        	}
        }
        else{
        	throw new BadCredentialsException("not support login way!");
        }
    }
}
